# -*- coding: utf-8 -*-
"""
Python代码示例
"""
import base64
import datetime
from hashlib import sha1
import hmac
import json 
import time
from loguru import logger

import requests
import psutil

# openapi地址
OPENAPI_BASE_URL = "https://api.su.baidu.com/%s"

ACCESS_KEY = "35f8a943622d4bc0bab04a428b0f262d"
SECRET_KEY = "7705152a2dec44388467bb80f676b491"

# 签名算法
SIGN_METHOD = "HMAC-SHA1"


logger.add("security_level_monitor_{time}.log",
           rotation="500 MB", # 文件过大就会重新生成一个文件
           encoding='utf-8',
           retention="10 days", # 一段时间后会清空
           compression="zip", # 保存zip格式
           )



def get_signature(sec_key, text):
    """
    计算签名
    """
    hmac_code = hmac.new(sec_key.encode(), text.encode(), sha1).digest()
    return base64.b64encode(hmac_code).decode()


def get_inited_common_params(path):
    """
    获取通用参数
    """
    param_map = {}

    auth_timestamp = str(int(time.time()))
    param_map['X-Auth-Access-Key'] = ACCESS_KEY
    param_map['X-Auth-Nonce'] = auth_timestamp
    param_map['X-Auth-Path-Info'] = path
    param_map['X-Auth-Signature-Method'] = SIGN_METHOD
    param_map['X-Auth-Timestamp'] = auth_timestamp

    return param_map


def smart_str(target_string):
    """
    处理字符串
    """
    if isinstance(target_string, bytes):
        return target_string.encode("utf-8")
    elif isinstance(target_string, str):
        return target_string
    
    return json.dumps(target_string)


def get_parsed_all_params(params):
    """
    拼接参数
    """
    keys = params.keys()
    sorted(keys)
    return "&".join(["%s=%s" % (str(k), smart_str(params[k])) for k in keys])


def get_request_header(path, query_params, body_params):
    """
    获取请求的Header
    """
    common_params = get_inited_common_params(path)
    all_params = {}
    headers = {}

    headers.update(common_params)

    all_params.update(common_params)
    all_params.update(query_params)
    all_params.update(body_params)

    all_params_str = get_parsed_all_params(all_params)

    sign = get_signature(SECRET_KEY, all_params_str)

    headers["X-Auth-Sign"] = sign

    return headers


def send_http_request(method='GET', url='', params=None, payload=None, headers=None):
    """
    发送Http请求
    """
    if params is None:
        params = {}
    if payload is None:
        payload = {}
    if headers is None:
        headers = {}
        
    # print('%s:%s' % (method, url))
    # print('Params:%s' % json.dumps(params, indent=4))
    # print('Payload:%s' % json.dumps(payload, indent=4))
    # print('Headers:%s' % json.dumps(headers, indent=4))
        
    resp = requests.request(method, url, params=params, data=json.dumps(payload), headers=headers)
    
    resp = '%s' % json.dumps(json.loads(resp.text), indent=4)
    
    return resp


def adjust_security_level_to_high():
    """
    示例
    """
    path = "v31/yjs/zones/5f607a5b8d210c751103688d/settings/security_level"
    params = {}

    payload = {}
    payload['value'] = 'high'

    headers = get_request_header(path, params, payload)

    url = OPENAPI_BASE_URL % path
    
    send_http_request("PATCH", url, params=params, payload=payload, headers=headers)


def adjust_security_level_to_under_attack():
    """
    示例
    """
    path = "v31/yjs/zones/5f607a5b8d210c751103688d/settings/security_level"
    params = {}

    payload = {}
    payload['value'] = 'under_attack'

    headers = get_request_header(path, params, payload)

    url = OPENAPI_BASE_URL % path
    
    send_http_request("PATCH", url, params=params, payload=payload, headers=headers)

'''
def current_security_level():
    """
    示例
    """
    path = "v31/yjs/zones/5f607a5b8d210c751103688d/settings/security_level"
    params = {}

    payload = {}
    payload['value'] = 'high'

    headers = get_request_header(path, params, payload)

    url = OPENAPI_BASE_URL % path
    
    response = send_http_request("PATCH", url, params=params, payload=payload, headers=headers)

    json_to_dict = json.loads(response)

    return json_to_dict.get("result").get("value")
'''

def loop_security_level():
        usage_cpu_average = 0
        security_status = ""
        
        while True:
            usage_cpu_average = 0
            for nums in range(0,3):
                usage_cpu_average += round(psutil.cpu_percent(interval=5))

            if usage_cpu_average / 3 < 50 and security_status == "":
                logger.info("cpu average usage is %.2f less than 50, sleep 10s..."%(usage_cpu_average / 3))
                time.sleep(10)
                break
            elif usage_cpu_average / 3 < 50 and security_status == "medium":
                logger.info("security level is medium, sleep 10s...")
                time.sleep(10)
                break
            elif usage_cpu_average / 3 > 50 and security_status != "under_attack":
                logger.warning("cpu average usage is %.2f over 50, try to change the security level to under_attack. "%(usage_cpu_average / 3))
                adjust_security_level_to_under_attack()
                security_status = "under_attack"
                logger.info("0 Security level is %s ..." % security_status)
            elif usage_cpu_average / 3 < 50 and security_status != "high":
                logger.info("cpu average usage is %.2f less than 50, try to change the security level back to high. "%usage_cpu_average / 3)
                adjust_security_level_to_high()
                security_status = "high"
                logger.info("1 Security level is %s ..." % security_status)
            else:
                logger.info("cpu average usage is %.2f, and security level is %s"%(usage_cpu_average / 3, security_status))
                time.sleep(5)


if __name__ == '__main__':
    while True:
        loop_security_level()

        

